import dayJs from 'dayjs';

// Date 时间格式化
const formatDateTime: any = (timeDate: any, format: any) => {
  if (timeDate && timeDate.toString().indexOf('-') > 0) {
    timeDate = timeDate.replace(new RegExp('-', 'g'), '/');
  }
  return dayJs(new Date(timeDate)).format(format); // YYYY-MM-DD HH:mm:ss
};

// Date 数据库时间转换
const formatTime: any = (timeDate: any, format: any) => {
  timeDate = new Date(
    new Date(timeDate.replace(/-/g, '/')).getTime() + +8 * 3600 * 1000,
  )
    .toISOString()
    .replace(/T/g, ' ')
    .replace(/\.[\d]{3}Z/, '');
  if (timeDate && timeDate.toString().indexOf('-') > 0) {
    timeDate = timeDate.replace(new RegExp('-', 'g'), '/');
  }
  return dayJs(new Date(timeDate)).format(format); // YYYY-MM-DD HH:mm:ss
};

const dateFormat: any = (date: any, fmt: string) => {
  let ret;
  const opt: any = {
    'Y+': date.getFullYear().toString(), // 年
    'm+': (date.getMonth() + 1).toString(), // 月
    'd+': date.getDate().toString(), // 日
    'H+': date.getHours().toString(), // 时
    'M+': date.getMinutes().toString(), // 分
    'S+': date.getSeconds().toString(), // 秒
    // 有其他格式化字符需求可以继续添加，必须转化成字符串
  };
  for (const k of Object.keys(opt)) {
    ret = new RegExp('(' + k + ')').exec(fmt);
    if (ret) {
      fmt = fmt.replace(
        ret[1],
        ret[1].length === 1 ? opt[k] : opt[k].padStart(ret[1].length, '0'),
      );
    }
  }
  return fmt;
};

const dateFormatNoRegExp: any = (value: any) => {
  if (!value) {
    return '1900-01-01';
  }
  const date = new Date(value);
  const y = date.getFullYear();
  let MM: any = date.getMonth() + 1;
  MM = MM < 10 ? '0' + MM : MM;
  let d: any = date.getDate();
  d = d < 10 ? '0' + d : d;
  let h: any = date.getHours();
  h = h < 10 ? '0' + h : h;
  let m: any = date.getMinutes();
  m = m < 10 ? '0' + m : m;
  let s: any = date.getSeconds();
  s = s < 10 ? '0' + s : s;
  return y + '-' + MM + '-' + d + ' ' + h + ':' + m + ':' + s;
};

// 距离转换
const formatDistance: any = (params: number) => {
  return params / 1000 + '公里';
};

// 时长转换
const formatDuration: any = (params: number) => {
  const hour: any = Math.floor(params / 3600);
  const minute: any = Math.floor(Math.floor(params % 3600) / 60);
  const second: any = Math.floor(params % 60);
  if (params > 3600) {
    return hour + '小时' + minute + '分钟' + second + '秒';
  } else if (params > 60) {
    return minute + '分钟' + second + '秒';
  } else {
    return second + '秒';
  }
};

// 手机号加密
const hidePhone: any = (params: string) => {
  return params.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2');
};

export default {
  formatDateTime,
  formatTime,
  dateFormat,
  dateFormatNoRegExp,
  formatDistance,
  formatDuration,
  hidePhone,
};
